import base from './base';
import * as API_REQ from '../apis/req';
import * as Util from './formUtil';
import { doSubmitForm,doSubmitReady,doSubmitPost,generateFormData } from './submit';
import { verifyCustomRegisterEvent } from './public/globalUtil';
import { verifyRemark } from './signUtil';
import * as _ from './public/common';
import * as type from '../constants/type';
import { getAntd,getEcCom,getLabel } from './convert';
import objectAssign from 'object-assign';
import { getStyleJson } from './formExport';
import {toJS} from "mobx";
import {message,Button} from "antd";

//金山 or 永中套红预览
export const openThPreview=()=>{
	let {globalStore,layoutStore} = base;
	const { commonParam,setLoading } = globalStore;
	const { requestid,workflowid } = toJS(commonParam);
	let {odocInfo} = layoutStore;
	odocInfo = toJS(odocInfo);
	let {showMouldId=-1,docid=-1,imagefileId=-1,wpsView=false,yozoView=false} = odocInfo.docParam;

	if(showMouldId<0){
		message.error(getLabel(23569,'套红模板没有设置，请和系统管理员联系！'));
		return ;
	}else if(docid<=0 || imagefileId<=0){
        message.error(getLabel(515738,'获取正文失败'));
        return ;
    }else if(!wpsView && !yozoView){
        message.error(getLabel(515745,'参数错误，请确认是否购买金山wps或者永中预览服务'));
    }else {
	    // // window.open("/spa/odoc/static/index.html#/main/offical/docTemplate?workflowid="+workflowid+"&selectvalue=-1&requestid="+requestid+"&docid="+docid+"&imagefileId="+imagefileId+"&openyozo="+yozoView+"&wpsEditor="+wpsView+"&fullView=1&_key=lqutvh","thPreview")
        // let iframe = document.createElement("iframe");
        // iframe.setAttribute('width','100%');
        // iframe.setAttribute('height','100%');
        // iframe.setAttribute('id','openModelComponent');
        // iframe.setAttribute("src","/spa/odoc/static/index.html#/main/offical/docTemplate?workflowid="+workflowid+"&selectvalue=-1&requestid="+requestid+"&docid="+docid+"&imagefileId="+imagefileId+"&openyozo="+yozoView+"&wpsEditor="+wpsView+"&fullView=1&_key=lqutvh");
        // document.getElementById("container").appendChild(iframe);
        oDocUtil.selectTemplate(false,1);
    }

}

//提交需反馈
export const doSubmitBack = () => {
	const { globalStore } = base;
	const { commonParam,rightMenu,submitParam = {}} = globalStore;
	const { iscreate ,selectNextFlowPattern } = commonParam;
	const { isFree} = rightMenu;
	//高级模式、简易模式，如果选了流转操作者直接提交
	if(isFree == "1" && iscreate == '1' && ((selectNextFlowPattern == 0 && submitParam.operatorids == "") || (selectNextFlowPattern != 0))){
		doFreeWorkflow();
	}else{
		globalStore.setSubmitToNodeId();
		doSubmitForm({actiontype:"requestOperation", src:"submit", needwfback:"1"});
	}
}

//提交不需反馈
export const doSubmitNoBack = () => {
	const { globalStore } = base;
	const { commonParam,rightMenu,submitParam = {} } = globalStore;
	const { iscreate,selectNextFlowPattern} = commonParam;
	const { isFree} = rightMenu;
    if(isFree == "1" && iscreate == '1' && ((selectNextFlowPattern == 0 && submitParam.operatorids == "") || (selectNextFlowPattern != 0))){
        doFreeWorkflow();
	}else{
		globalStore.setSubmitToNodeId();
		doSubmitForm({actiontype:"requestOperation", src:"submit", needwfback:"0"});
	}
}

//流程保存
export const doSave_nNew = (closePage=false) => {
	doSubmitForm({actiontype:"requestOperation", src:"save", closePage:closePage});
}

//提交后确认按钮
export const doSubmit_Pre = (src) => {
	doSubmitForm({actiontype:"requestOperation", src:src||"submit"});
}

//流程督办
export const doSupervise = () => {
	const { globalStore } = base;
	globalStore.controlDialogVisible(type.DO_SUPERVISE, true);
}

//流程干预
export const doIntervenor = () =>{
	doSubmitForm({actiontype:"requestOperation", src:"intervenor"});
}

export const doIntervenorDialog=(visible)=>{
	const { globalStore } = base;
	globalStore.controlDialogVisible(type.Intervention_dialog, visible);
}

//批注需反馈
export const doRemark_nBack = () => {
	doSubmitForm({actiontype:"remarkOperation", src:"save", needwfback:"1"});
}

//批注不需反馈
export const doRemark_nNoBack = () => {
	doSubmitForm({actiontype:"remarkOperation", src:"save", needwfback:"0"});
}

//流程打印签字意见选择
export const  doPrintRequestLog = (gwurl)=>{
	let  params = {showGwForward:true};
	const {commonParam ,submitParam, changeSubmitParam,setTabKey,batchControlVariableMap,controlDialogVisible,loadRightMenu} = base.globalStore;
	const {requestid,nodeid,f_weaver_belongto_userid,f_weaver_belongto_usertype, workflowid} = commonParam;
	const {agentType, agentorByAgentId} =  submitParam;
	params.requestid = requestid;
	params.nodeid = nodeid;
	params.workflowid = workflowid;
	params.fromform  = true;
	params['f_weaver_belongto_userid'] = f_weaver_belongto_userid;
	params['f_weaver_belongto_usertype'] = f_weaver_belongto_usertype;
	params.agentType = agentType;
	params.agentorByAgentId = agentorByAgentId;
	const actions  = {
		'changeSubmitParam':changeSubmitParam,
		'setTabKey':setTabKey,
		'batchControlVariableMap':batchControlVariableMap,
		'controlDialogVisible':controlDialogVisible,
		'closeRequestPage':Util.closeRequestPage,
		'refreshRightMenu' : loadRightMenu,
	};
	batchControlVariableMap({
		'forwardParams':params,
		'callBackActions':actions,
		'isRelaodLogList':false,
		'isPrintShow':true,
		'gwurl':gwurl
	});
	controlDialogVisible('isShowGWForwardDialog',true);
}


const doPrintWorkflow=()=>{
	verifyCustomRegisterEvent(WfForm.OPER_PRINT, ()=>{
		const { commonParam , urlParams = {}} = base.globalStore;
		const { requestid,wfmonitor,isurger,f_weaver_belongto_userid,f_weaver_belongto_usertype,wfTestStr } = commonParam;
		const { isrequest = '',isfromreport='',reportid='',isfromflowreport='', isfromchatshare=''} = urlParams;
		let { authSignatureStr = '',authStr = '' } = urlParams;
		if (!authSignatureStr) authSignatureStr = commonParam.authSignatureStr;
		if (!authStr) authStr = commonParam.authStr;
		const ismonitor = wfmonitor ? "1" : "0";
		const urger = isurger ? "1" : "0";
		const printurl = "/workflow/request/PrintRequestForward.jsp?";
		let printUrlParams = `requestid=${requestid}&ismonitor=${ismonitor}&urger=${urger}&f_weaver_belongto_userid=${f_weaver_belongto_userid}&f_weaver_belongto_usertype=${f_weaver_belongto_usertype}&wfTestStr=${wfTestStr}`;
		if(authSignatureStr) printUrlParams += `&authSignatureStr=${authSignatureStr}`;
		if(authStr) printUrlParams += `&authStr=${authStr}`;
		if(isrequest) printUrlParams += `&isrequest=${isrequest}`;
		if(isfromreport) printUrlParams += `&isfromreport=${isfromreport}`;
		if(isfromflowreport)printUrlParams += `&isfromflowreport=${isfromflowreport}`;
		if (isfromchatshare) printUrlParams += `&isfromchatshare=${isfromchatshare}`;
		if(reportid) printUrlParams += `&reportid=${reportid}`;
		openFullWindowHaveBar(printurl+printUrlParams);
	});
}

//流程打印
export const doPrintRequest = () => {
	/*const { commonParam } = base.globalStore;
	const {signFilter} = commonParam;
	if(signFilter=='1'){
		doPrintRequestLog();
	}else{*/
		doPrintWorkflow();
	/*}*/
}

//流程暂停
export const doStop = () => {
	doFunctionLink("stop");
}

//流程撤销
export const doCancel = () => {
	doFunctionLink("cancel");
}

//流程启用
export const doRestart = () => {
	doFunctionLink("restart");
}

const doFunctionLink = (flag) => {
	const { commonParam,submitParam } = base.globalStore;
    const { openByDefaultBrowser } = submitParam;
	const { requestid,f_weaver_belongto_userid,f_weaver_belongto_usertype } = commonParam;
	let content = "";
	
	switch(flag){
		case 'stop':
			content = getLabel(26156,'您确定要暂停当前流程吗？');
			break;
		case 'cancel':
			content = getLabel(26157,'您确定要撤销当前流程吗 ？');
			break;
		case 'restart':
			content = getLabel(26158,'您确定要启用当前流程吗？');
			break;
	}
	getAntd().Modal.confirm({
		title:getLabel(131329,'信息确认'),
		content: content,
		okText:getLabel(826,'确定'),
		cancelText:getLabel(201,'取消'),
		onOk() {
			API_REQ.functionLink({
				flag: flag,
				requestid: requestid,
				f_weaver_belongto_userid: f_weaver_belongto_userid,
				f_weaver_belongto_usertype: f_weaver_belongto_usertype,
                openByDefaultBrowser:openByDefaultBrowser
			}).then(data => {
				Util.closeRequestPage(false);
			});
		}
	});
}

//强制收回
export const doRetract = () => {
	verifyCustomRegisterEvent(WfForm.OPER_TAKEBACK, ()=>{
		const { commonParam,submitParam } = base.globalStore;
		const { requestid,workflowid,f_weaver_belongto_userid,f_weaver_belongto_usertype } = commonParam;
		const { openByDefaultBrowser } = submitParam;
		API_REQ.functionLink({
			flag: "rb",
			requestid: requestid,
			workflowid: workflowid,
			f_weaver_belongto_userid: f_weaver_belongto_userid,
			f_weaver_belongto_usertype: f_weaver_belongto_usertype,
            openByDefaultBrowser: openByDefaultBrowser
		}).then((data) => {
			if(data.success){
                // getAntd().message.success(data.msg,undefined,()=>{
                //     Util.reloadRequestPage({requestid});
				// });
                Util.reloadRequestPage({requestid, sessionkey : data.sessionkey});
			}else{
                getAntd().message.error(data.msg);
			}
		});
	});
}

//强制归档
export const doDrawBack = () => {
	const { globalStore } = base;
	const { commonParam,baseParam,continuationProcessInfo } = globalStore;
	const { requestid,needconfirm } = commonParam;
	const drawBackFun = () => {
		if(verifyRemark({src:'arichive'})){
			const formDatas = generateFormData();   //表单字段参数
			const {submitParam} = globalStore;
			const allParams = {...submitParam, ...formDatas, flag:"ov", fromflow:1};
			globalStore.setLoading(true);
			API_REQ.functionLink(allParams).then(data =>{
				globalStore.setLoading(false);
				if(commonParam.belongTest){		//流程测试直接刷页面
					Util.reloadRequestPage({requestid});
					try {
						parent.window.workflowAutoTestUtil.returnStatus("SUCCESS");
					} catch (e) {
						if (window.console) console.log(e);
					}
				}else if(data.isShowChart && data.isShowChart == "1"){
					globalStore.setCloseNeedPrompt(false);
					const urlParam = objectAssign({}, baseParam, {isfromtab:submitParam.isfromtab, showE9Pic:"1",isFromAutodirect:"1",isFromWfForm:true});
					Util.reloadListPage();

					//跳转流程图，拼接连续处理参数
					Util.appendContinuationParams(urlParam);

					Util.gotoPage("/workflow/request/WorkflowDirectionNew.jsp", urlParam);
				}else{
					Util.closeRequestPage(false);
				}
			});
		}
	}
	if(needconfirm == '1'){
		getAntd().Modal.confirm({
			title:getLabel(131329,'信息确认'),
			content: getLabel(24703,'您确定将该流程强制归档吗？'),
			okText:getLabel(826,'确定'),
			cancelText:getLabel(201,'取消'),
			onOk() {
				drawBackFun();
			},
			onCancel(){
				return;
			}
		});
	}else{
		drawBackFun();
	}
}

//打印日志
export const doPrintViewLog = () => {
	const { globalStore,printLogStore } = base;
	const { baseParam } = globalStore;
	const { requestid,f_weaver_belongto_userid,f_weaver_belongto_usertype } = baseParam;
	printLogStore.setBaseParams({requestid,f_weaver_belongto_userid,f_weaver_belongto_usertype});
	printLogStore.setCloseEvent(() =>{
		globalStore.controlDialogVisible(type.PRINT_LOG, false);
	});
	globalStore.controlDialogVisible(type.PRINT_LOG, true);
}

//新建任务列表
export const openTaskList = () => {
	const { requestid } = base.globalStore.baseParam;
	openWin("/spa/workrelate/static/index.html#/main/workrelate/task/otherTastList?requestids=" + requestid);
}

//新建任务
export const doCreateTask = () => {
	const { requestid } = base.globalStore.baseParam;
	openWin("/spa/workrelate/static/index.html#/main/workrelate/task/taskAdd?requestids=" + requestid);
}

const openWin = (url, showw, showh) => {
	if(showw == null || typeof(showw) == "undefined") showw = 900;
	if(showh == null || typeof(showh) == "undefined") showh = 520;
	var redirectUrl = url;
	var height = screen.height;
	var width = screen.width;
	var top = (height - showh) / 2;
	var left = (width - showw) / 2;
	var szFeatures = "top=" + top + ",";
	szFeatures += "left=" + left + ",";
	szFeatures += "width=" + showw + ",";
	szFeatures += "height=" + showh + ",";
	szFeatures += "directories=no,";
	szFeatures += "status=yes,";
	szFeatures += "menubar=no,";
	szFeatures += "scrollbars=yes,";
	szFeatures += "resizable=yes"; //channelmode
	window.open(redirectUrl, "", szFeatures);
}

//退回确认节点
export const doReject_New = () => {
	if(verifyRemark({src:'reject'})){
		const { globalStore,rejectStore } = base;
		const { commonParam } = globalStore;
		const { requestid,workflowid,nodeid,f_weaver_belongto_userid,f_weaver_belongto_usertype } = commonParam;
		API_REQ.judgeRejectWay({requestid,workflowid,nodeid,f_weaver_belongto_userid,f_weaver_belongto_usertype}).then(data =>{
			const { rejecttype,params } = data;
			if(rejecttype === 0){
				sureReject();
			}else if(rejecttype === 1){
				const { RejectToNodeid,newRejectNodeIds = '' } = params;
				sureReject({'RejectToNodeid':RejectToNodeid,'newRejectNodeIds' : newRejectNodeIds });
			}else if(rejecttype === 2){	//弹窗选择退回节点及提醒节点
				rejectStore.setBaseParams(params);
				rejectStore.setChooseInfo(data.chooseInfo);
				const { RejectToNodeid,newRejectNodeIds = '' } = params;
				rejectStore.setConfirmEvent((rejectParams) =>{
					if(!_.isEmpty(rejectParams)){
						const { rejectNodeKey="",remindNodeid="",isSubmitDirect="" } = rejectParams;
						let appendParams = {'RejectNodes' : remindNodeid, 'isSubmitDirect' : isSubmitDirect};
						if(rejectNodeKey) {
                            const rejectNodeArr = rejectNodeKey.split("_");
                            appendParams['RejectToNodeid'] = rejectNodeArr[0];
                            appendParams['RejectToType'] = rejectNodeArr[1];
						}
						if(RejectToNodeid) {
                            appendParams['RejectToNodeid'] = RejectToNodeid;
						}
						if(newRejectNodeIds) appendParams['newRejectNodeIds'] = newRejectNodeIds;
						sureReject(appendParams);
					}
					globalStore.controlDialogVisible(type.REJECT_CHOOSE, false);
				});
				rejectStore.setCancelEvent(() =>{
					globalStore.controlDialogVisible(type.REJECT_CHOOSE, false);
				});
				globalStore.controlDialogVisible(type.REJECT_CHOOSE, true);		//需最后显示弹窗
			}
		});
	}
}

//流程退回
export const sureReject = (rejectParams = {}) => {
	const { commonParam } = base.globalStore;
	const { needconfirm } = commonParam;
	let params = objectAssign({},{src:"reject", actiontype:"requestOperation",'isFirstSubmit':'0'},rejectParams);
	if(needconfirm == "1")
		_.merge(params, {src:"save", isaffirmance:"1", isaffirmanceSrc:"reject"});
	doSubmitReady(params);
}

//表单修改日志
export const doViewModifyLog = () => {
	const { globalStore } = base;
	globalStore.controlDialogVisible(type.FORM_MODIFY_LOG, true);
}

//流程删除
export const doDelete = () => {
	getAntd().Modal.confirm({
		title: getLabel(131329,'信息确认'),
		content: getLabel(16667,' 你确定删除该工作流吗？ '),
		okText:getLabel(826,'确定'),
		cancelText:getLabel(201,'取消'),
		onOk(){
			verifyCustomRegisterEvent(WfForm.OPER_DELETE, () =>{
				doSubmitPost({src:"delete", actiontype:"requestOperation"});
			})
		}
	});
}

//提交
export const doSubmitDirect = (subfun) => {
	const { globalStore, secondAuthStore} = base;
	const { submitParam,rightMenu,setSubmitToNodeId } = globalStore;
	const { ifchangstatus } = submitParam;
	const { hasback, hasnoback,lastnodeid } = rightMenu;
    setSubmitToNodeId(true);
	if(ifchangstatus != "" && (hasback == "1" || (hasback == "" && hasnoback == ""))) {
		if(subfun == "Affirmance") {
			doAffirmanceBack();
		} else {
			secondAuthStore.setIsSubmitDirect(1);
			doSubmitBack();
		}
	} else {
		if(subfun == "Affirmance") {
			doAffirmanceNoBack();
		} else {
			secondAuthStore.setIsSubmitDirect(1);
			doSubmitNoBack();
		}
	}
}


//公文转办
export const doGwzbTask = (resourceid) =>{
	    var useNewModal = window.useNewModal;
		if(useNewModal == undefined){
			let _interval = setInterval(function(){
				useNewModal = window.useNewModal;
				if(useNewModal != undefined){
					clearInterval(_interval);
				}
			},10)
		}
		if(useNewModal == 1){
			window.doGwzb();
		}else{
			let  params = {showGwForward:true};
			const {commonParam ,submitParam, changeSubmitParam,setTabKey,batchControlVariableMap,controlDialogVisible,loadRightMenu} = base.globalStore;
			const {requestid,nodeid,f_weaver_belongto_userid,f_weaver_belongto_usertype, workflowid} = commonParam;
			const {agentType, agentorByAgentId} =  submitParam;
			params.requestid = requestid;
			params.nodeid = nodeid;
			params.workflowid = workflowid;
			params.fromform  = true;
			params['f_weaver_belongto_userid'] = f_weaver_belongto_userid;
			params['f_weaver_belongto_usertype'] = f_weaver_belongto_usertype;
			params.agentType = agentType;
			params.agentorByAgentId = agentorByAgentId;
			const actions  = {
				'changeSubmitParam':changeSubmitParam,
				'setTabKey':setTabKey,
				'batchControlVariableMap':batchControlVariableMap,
				'controlDialogVisible':controlDialogVisible,
				'closeRequestPage':Util.closeRequestPage,
				'refreshRightMenu' : loadRightMenu,
			};
			batchControlVariableMap({
				'forwardParams':params,
				'callBackActions':actions,
				'isRelaodLogList':false,
				'isPrintShow':false,
				'gwurl':''
			});
			controlDialogVisible('isShowGWForwardDialog',true);
		}

}

//转发、意见征询、转办等
const controlForward = (params = {}) =>{
	const { forwardflag } = params;
	let opertype = WfForm.OPER_FORWARD;
	if(forwardflag == "2")
		opertype = WfForm.OPER_ASKOPINION;
	else if(forwardflag == "3")
		opertype = WfForm.OPER_TURNHANDLE;
	else if(forwardflag == "4")
		opertype = WfForm.OPER_TURNREAD;
	else if(forwardflag == "5")
	    opertype = WfForm.OPER_TAKFROWARD;

	verifyCustomRegisterEvent(opertype, () =>{
		const {commonParam ,submitParam, changeSubmitParam,setTabKey,batchControlVariableMap,controlDialogVisible,loadRightMenu} = base.globalStore;
		const {requestid,nodeid,f_weaver_belongto_userid,f_weaver_belongto_usertype, workflowid} = commonParam;
		const {agentType, agentorByAgentId} =  submitParam;
		params.requestid = requestid;
		params.nodeid = nodeid;
		params.workflowid = workflowid;
		params.fromform  = true;
		params['f_weaver_belongto_userid'] = f_weaver_belongto_userid;
		params['f_weaver_belongto_usertype'] = f_weaver_belongto_usertype;
		params.agentType = agentType;
		params.agentorByAgentId = agentorByAgentId;
		const actions  = {
			'changeSubmitParam':changeSubmitParam,
			'setTabKey':setTabKey,
			'batchControlVariableMap':batchControlVariableMap,
			'controlDialogVisible':controlDialogVisible,
			'closeRequestPage':Util.closeRequestPage,
			'refreshRightMenu' : loadRightMenu,
		};
		batchControlVariableMap({
			'forwardParams':params,
			'callBackActions':actions,
			'isRelaodLogList':false
		});
		controlDialogVisible('isShowForwardDialog',true);
	});
}

//转发
export const doReviewE9 = (destuserid = '') => {
	controlForward({showForward:true, forwardflag:"1",forwardOperators:destuserid});
}



//传阅
export const doChuanyue = (destuserid = '') => {
	controlForward({showForward:true, forwardflag:"4"});
}

//转发收回
export const doReviewE9Back = () => {
    const { globalStore } = base;
    const {commonParam,batchControlVariableMap,controlDialogVisible,loadRightMenu} = globalStore;
    const { requestid } = commonParam;
    const actions  = {
        'refreshRightMenu' : ()=>{
            //loadRightMenu({}); //刷新右键菜单
            Util.reloadRequestPage({requestid});
		},
		"controlDialogVisible" : (isShow)=>{
            controlDialogVisible(type.FORWARD_BACK,isShow);// 关闭收回弹框
		},
        'batchControlVariableMap': null,//batchControlVariableMap,
    };
    batchControlVariableMap({
        'callBackActions':actions,
    });
    controlDialogVisible(type.FORWARD_BACK, true);
}

/**
 * 意见征询收回
 */
export const doTakeBack = () => {

    const { globalStore } = base;
    const {commonParam, submitParam} = globalStore;
	const { requestid,f_weaver_belongto_userid,f_weaver_belongto_usertype, workflowid } = commonParam;
	const { agentType, takisremark, agentorByAgentId,openByDefaultBrowser } = submitParam;
    API_REQ.doTakeBack({workflowid, requestId : requestid,f_weaver_belongto_userid,f_weaver_belongto_usertype,agentType,takisremark,agentorByAgentId,openByDefaultBrowser:openByDefaultBrowser}).then((reVal)=>{
        Util.reloadRequestPage({requestid});
    });
}

//转办需反馈
export const doReviewback3 = (resourceid) => {
	controlForward({showForward:true, forwardflag:"3", needwfback:"1"});
}

//转办
export const doReview3 = (resourceid) =>{
	controlForward({showForward:true, forwardflag:"3"});
}

//意见征询
export const doReview2 = (resourceid) =>{
	controlForward({showForward:true, forwardflag:"2"});
}

//多级意见征询
export const doMultiTak = (resourceid) =>{
    controlForward({showForward:true, forwardflag:"2", isMulitTak:true});
}

//征询转办需反馈
export const doTakForward_Back = (resourceid) =>{
	controlForward({showForward:true, forwardflag:"5", needwfback : '1'});
}

//征询转办不需反馈
export const doTakForward_noBack = (resourceid) =>{
	controlForward({showForward:true, forwardflag:"5", needwfback : '0'});
}

//结束征询
export  const doTakEnd = () => {
	const { globalStore } = base;
	const {commonParam, submitParam, rightMenu = {}} = globalStore;
	const { rightMenuNames = {} } = rightMenu;
	const { requestid,workflowid } = commonParam;
	const { agentType, agentorByAgentId,openByDefaultBrowser } = submitParam;
	let label = getLabel(510675,'确定要结束意见征询吗？');
	if(rightMenuNames['TAKEND_0']) {
		label = getLabel(519120, '确定要{1}吗？').replace("{1}", rightMenuNames['TAKEND_0']);
	}
	getAntd().Modal.confirm({
		title:getLabel(131329,'信息确认'),
		okText:getLabel(826,'确定'),
		cancelText:getLabel(201,'取消'),
		content: label,
		onOk(){
			API_REQ.doTakEnd({
				requestid: requestid,
				workflowid,
				agentType,
				agentorByAgentId,
                openByDefaultBrowser:openByDefaultBrowser
			}).then(data => {
				if(!data.result && data.msg) {
					getAntd().Modal.warning({
						content: data.msg,
						okText: getLabel(83446,'确定'),
						showClose: false,
						onOk() {
                            Util.reloadRequestPage({requestid});
						}
					})
				} else {
					Util.reloadRequestPage({requestid});
				}
			});
		}
	});
}

//转办不需反馈
export const doReviewnoback3 = (resourceid) =>{
	controlForward({showForward:true, forwardflag:"3", needwfback:"0"});
}

export const doTd253574 = (funParams = {}) =>{
	const {forwardOperators = ''} = funParams;
	const params = {showForward:true, forwardflag:"1", forwardOperators, feedbacksign:"4"};
	controlForward(params);
}

//超时设置
export const onNewOverTime = () =>{
	const { globalStore,overTimeStore } = base;
	const { baseParam } = globalStore;
	overTimeStore.setBaseParams(baseParam);
	overTimeStore.setCloseEvent(() =>{
		globalStore.controlDialogVisible(type.OVERTIME_SETTING, false);
	});
	globalStore.controlDialogVisible(type.OVERTIME_SETTING, true);
}

//撤回
export const doWithdraw = (destuserid = '') => {
	const { globalStore,requestWithdrawStore } = base;
	const { baseParam } = globalStore;
	requestWithdrawStore.doInit(baseParam);
	requestWithdrawStore.setCloseEvent(() =>{
		globalStore.controlDialogVisible(type.WORKFLOW_WITHDRAW, false);
	});
	globalStore.controlDialogVisible(type.WORKFLOW_WITHDRAW, true);
}

//新建流程
export const onNewRequest = (workflowid,requestid,agent) => {
	const { belongUserStr } = base.globalStore;
	const urlParam = `workflowid=${workflowid}&isagent=${agent}&reqid=${requestid}${belongUserStr}`;
	openFullWindowHaveBar(`/workflow/request/CreateRequestForward.jsp?${urlParam}`);
}

/**
 * 新建流程
 * @param workflowid
 * @param requestid
 * @param nodeId
 * @param menuId
 */
export const onNewRequest2 = (workflowid,requestid,nodeId,menuId,requestType) => {
	const callFun = ()=>{
        const urlParam = `workflowid=${workflowid}&reqid=${requestid}&createFlowNodeid=${nodeId}&nodecustomid=${menuId}`;
        openFullWindowHaveBar(`/workflow/request/CreateRequestForward.jsp?${urlParam}`);
		Util.reloadRequestPage({requestid: requestid});
	}

	(requestType != 0) && doSubmitForm({
        actiontype:"requestOperation",
        src:"save",
        saveCallFun : callFun
    });

	(requestType == 0) && callFun();


}

//新建短信
export const onNewSms = (wfid, nodeid, reqid, menuid,isurger) => {
	const { globalStore } = base;
	const { belongUserStr } = globalStore;
	let params = {};
	if(isurger == 1){//督办催办短信
		params = {src:'supervise',requestid:reqid};
	}else{
		params = {...belongUserStr, ...{workflowid:wfid, nodeid:nodeid, requestid:reqid, menuid:menuid}};
	}
	globalStore.controlVariableMap(type.SEND_SMS_PARAMS, params);
	globalStore.controlDialogVisible(type.SEND_SMS, true);
}

//催办邮件
export const onNewEmail = (reqid) => {
	const { globalStore } = base;
	API_REQ.getSendEmailInfo({requestid:reqid}).then((data)=>{
       if(data.result){
			let params = data.fwquery || {};
        	globalStore.controlVariableMap(type.SEND_MAIL_PARAMS, params);
			globalStore.controlDialogVisible(type.SEND_MAIL, true);
       }
    });
}

//新建微信
export const onNewChats =(wfid, nodeid, reqid, menuid) => {
	const { belongUserStr } = base.globalStore;
	const urlParam = `workflowid=${wfid}&nodeid=${nodeid}&reqid=${reqid}&actionid=dialog&menuid=${menuid}${belongUserStr}`;
	const dialog = new window.top.Dialog();
	dialog.currentWindow = window;
	dialog.Title = getLabel(32818,"新建微信 ");
	dialog.Width = 1000;
	dialog.Height = 350;
	dialog.Drag = true;
	dialog.maxiumnable = true;
	dialog.URL = `/wechat/sendWechat.jsp?${urlParam}`;
	dialog.show();
}

//关于版本
export const aboutVersion = (versionid) => {
	getAntd().Modal.warning({
			title: getLabel(131329,'信息确认'),
	    content: getLabel(386181,'当前是') + "V" + versionid + "  " +  getLabel(567,"版本"),
			okText:getLabel(826,'确定'),
	    onOk() {
	    	return;
	    }
	});
}

//流转设定
export const doFreeWorkflow = () =>{
	const { globalStore } = base;
	const { commonParam,rightMenu,variableMap,batchControlVariableMap,controlDialogVisible, baseParam} = globalStore;
	const { iscreate,authSignatureStr,authStr,wfTestStr,belongTest, selectNextFlowPattern} = commonParam;
	const { iscnodefree,isFree,freeNode = {} ,isAllowNodeFreeFlow} = rightMenu;
	if(iscreate == '1' && selectNextFlowPattern != 0) {
		window.localStorage.setItem('WfFormIsDefaultOpenFreeFlowSetDialog','1');
		doSubmitForm({actiontype:"requestOperation", src:"save"});
	} else {
		if(selectNextFlowPattern == 0){//简易模式 0才是建议模式
			const{tabKey,setTabKey} = globalStore;
			if(tabKey !== "form"){
				setTabKey("form")
				setTimeout(()=>{
					Util.scrollDom(".wf-req-freeWorkflowSimple",true,getLabel(520577,"请确认流转设定设置"));
				},500)
			}else{
				Util.scrollDom(".wf-req-freeWorkflowSimple",true,getLabel(520577,"请确认流转设定设置"));
			}
		}else {
			const { WeaTools } = getEcCom();
			let chartParams  = {
				...toJS(baseParam),
				isAllowNodeFreeFlow,
				isFree,
				authSignatureStr,
				authStr,
				wfTestStr,
				'isFlowModel':0,
				'isReadOnlyModel':false,
				'showE9Pic':1,
				'isFromWfForm':true,
				belongTest:belongTest ? 1 : 0
			};
			const workflowFreeFlowSetDialog = WeaTools.createDialog({
				title: getLabel(21781,'流转设定'),
				icon:'icon-coms-workflow',
				iconBgcolor:'#0079DE',
				moduleName: "workflow",
				url: `/workflow/workflowDesign/readOnly-index.html?${Util.buildUrlStr(chartParams)}`,
				style: {width:window.innerWidth*0.9, height:window.innerHeight*0.9},
				maxHeight:10000,
				callback: function(datas,dialog){
					getAntd().message.destroy();
					getAntd().message.success(getLabel(83551,'保存成功！'));
					if(dialog) dialog.hide();
					const {isNeedFlowFreeNodeTips = false,canSubmitToRejectNode = false} = datas;
					batchControlVariableMap({'isNeedFlowFreeNodeTips':isNeedFlowFreeNodeTips,'canSubmitToRejectNode':canSubmitToRejectNode});
				},
				onCancel: function(a){
					let closeFunc = variableMap.get('FREE_FLOW_SET_CLOSE_FUNC');
					closeFunc && closeFunc();
				}
			},undefined,(dialog) => {
				if(dialog){
					dialog.show();
				}
			});
		}
	}
}

/**
 *
 * @param subwfid
 * @param workflowNames
 * @param requestType 0：已办、1：待办
 */
export const triSubwf2 = (subwfid, workflowNames,requestType) =>{
	const { globalStore } = base;
	const { commonParam } = globalStore;
	if(commonParam.belongTest){
		getAntd().Modal.warning({
			title: getLabel(131329,'信息确认'),
			content: getLabel(386182,"流程测试状态不允许手动触发子流程"),
			okText: getLabel(83446,`确定`)
		});
		return;
	}
	workflowNames = workflowNames.replace(new RegExp(',',"gm"),'\n');
	getAntd().Modal.confirm({
		title:getLabel(131329,'信息确认'),
		okText:getLabel(826,'确定'),
		cancelText:getLabel(201,'取消'),
		content: getLabel(25394,'确定触发') + ":"+workflowNames+getLabel(386183,"流程吗?"),
		onOk(){

			const callFun = ()=>{
                globalStore.setLoading(true);
                const { requestid,nodeid,f_weaver_belongto_userid,f_weaver_belongto_usertype } = commonParam;
                const params = {requestId:requestid, nodeId:nodeid, paramSubwfSetId:subwfid, f_weaver_belongto_userid, f_weaver_belongto_usertype};
                API_REQ.triggerSubWf(params).then(data => {
                    getAntd().Modal.warning({
                        title:getLabel(131329,'信息确认'),
                        content: data.msg,
                        okText:getLabel(83446,`确定`),
                        showClose: false,
                        onOk() {
                            globalStore.setLoading(false);
                            Util.reloadRequestPage({requestid: requestid});
                        }
                    });
                });
			}

            //先执行保存
            (requestType != 0) && doSubmitForm({
                actiontype:"requestOperation",
                src:"save",
                saveCallFun : callFun
            });
            (requestType == 0) && callFun();
		}
	});
}

export const doAffirmanceBack = () =>{
	base.globalStore.setSubmitToNodeId();
	doSubmitForm({actiontype:"requestOperation", src:"save", needwfback:"1", isaffirmance:"1"});
}

export const doAffirmanceNoBack = () =>{
	base.globalStore.setSubmitToNodeId();
	doSubmitForm({actiontype:"requestOperation", src:"save", needwfback:"0", isaffirmance:"1"});
}

//分享到EM
export const doShare = () =>  {
	let isE9 = true;
	if (isE9) {
		const { shareStore ,globalStore } = base;
		const { urlParams, commonParam, invalidParam } = globalStore;
		const { sharer, firstSharer} = urlParams;
		const { setMsgInfo } = shareStore;
		setMsgInfo(commonParam, invalidParam, firstSharer);
		globalStore.controlDialogVisible(type.SHARE_WORKFLOW, true);
	} else {
		const { commonParam } = base.globalStore;
		const { requestid } = commonParam;
		const { mainData } = base.layoutStore;
		const requestname = mainData.has("field-1") ? mainData.get("field-1").value : "";
		const returnjson = '[{"sharetype":"workflow","sharetitle":"' + requestname + '","objectname":"FW:CustomShareMsg","shareid":"' + requestid + '"}]';
		const url = "/social/im/SocialHrmBrowserForShare.jsp?sharejson=" + encodeURIComponent(returnjson);
		const diag = new window.top.Dialog();
		diag.currentWindow = window;
		diag.Modal = true;
		diag.Drag = true;
		diag.Width = 400;
		diag.Height = 500;
		diag.ShowButtonRow = false;
		diag.Title = getLabel(129144, "分享");
		diag.URL = url;
		diag.openerWin = window;
		diag.show();
		document.body.click();
	}
	
}

//流程编辑
export const doEdit = () =>{
	const { requestid } = base.globalStore.commonParam;
	Util.reloadRequestPage({reEdit:"1", requestid:requestid});
}

//明细导入
export const doImportDetail = () =>{
	const { commonParam,controlDialogVisible } = base.globalStore;
	const { requestid,workflowid,nodeid } = commonParam;
	if(requestid == "-1"){
		getAntd().Modal.confirm({
			title:getLabel(131329,'信息确认'),
			content:getLabel(21798,"流程数据还未保存，现在保存吗? "),
			okText:getLabel(826,'确定'),
			cancelText:getLabel(201,'取消'),
			onOk(){
				doSubmitForm({actiontype:"requestOperation", src:"save"});
			}
		});
	}else{
        controlDialogVisible(type.IMPORT_WF_DETAIL_MODAL,true);
	}
}

//正式系统--改进建议
export const openProductSuggest = () =>{
	let url = "/formmode/view/AddFormMode.jsp?mainid=0&modeId=125&formId=-290&type=1";
	let dialog = new window.top.Dialog();
	dialog.currentWindow = window;
	dialog.Width = 1200;
	dialog.Height = 600;
	dialog.Modal = true;
	dialog.Title = getLabel(128666,'改进建议');
	dialog.URL =url;
	dialog.isIframe=false;
	dialog.show();
	let hasinit  = false;
	let count = 1;
	try{
		var timer = setInterval(function(){
			var doc1 = $(window.top.document).find("iframe[id^=_DialogFrame_]");
			if(doc1 && doc1.length > 0){
				var doc2 = $(doc1[0].contentWindow.document).find("iframe[name='tabcontentframe']");
				if(doc2 && doc2.length > 0){
					var _tempdocument = doc2[0].contentWindow.document;
					if(_tempdocument){
						var hbbox  = $(_tempdocument).find('.hbBox');
						if(hbbox && hbbox.length > 0){
							hasinit = true;
							hbbox.css("padding","10px 40px");
						}
					}
				}
			}
			if(hasinit || count > 20){
				clearInterval(timer);
			}
			count++;
		},20);
	}catch(e){}
}

//返回到待办
export const doBack = () => {
	const { globalStore } = base;
	globalStore.setCloseNeedPrompt(true);
	window.location.href = "/spa/workflow/index_mobx.jsp#/main/workflow/listDoing";
}
//返回到待办
export const do_Intervention = () => {
	const { globalStore } = base;
	const { controlDialogVisible } = globalStore;
	controlDialogVisible(type.EnableProcessIntervention,true);
}

//表单导出
export const toExcel = () =>{
    localStorage.setItem("fun", window.onbeforeunload);
    window.onbeforeunload = null;
    getStyleJson().then((value) => {
		API_REQ.getExportedExcel(value);
	});
    window.onbeforeunload = localStorage.getItem("fun");
}

/**
 * 自定义操作菜单
 * @param reqid
 * @param wfid
 * @param menuid
 * @param nodeid
 */
export const onCustomOpt =(reqid,wfid, menuid,nodeid) =>{
	const { globalStore } = base;
	const { commonParam , urlParams = {}} = globalStore;
	const { requestid,wfmonitor,isurger,f_weaver_belongto_userid,f_weaver_belongto_usertype,isremark } = commonParam;
	const ismonitor = wfmonitor ? "1" : "0";
	const urger = isurger ? "1" : "0";


		//controlDialogVisible(type.IMPORT_WF_DETAIL_MODAL,true);
		//alert("onCustomOpt"+" menuid = "+menuid);
		const params = {requestId:reqid, nodeId:nodeid, workflowId:wfid,setid:menuid,ismonitor:ismonitor,urger:urger,f_weaver_belongto_userid:f_weaver_belongto_userid, f_weaver_belongto_usertype:f_weaver_belongto_usertype};
		try {
			API_REQ.getCustomOperation(params).then(data => {
				let hassave =  data.ismustsave ;
				if(requestid == "-1"&&hassave==='1'){//需要保存
					getAntd().Modal.confirm({
						title:getLabel(131329,'信息确认'),
						content:getLabel(21798,"流程数据还未保存，现在保存吗? "),
						okText:getLabel(826,'确定'),
						cancelText:getLabel(201,'取消'),
						onOk(){
							doSubmitForm({actiontype:"requestOperation", src:"save"});
						}
					});
				}else {

					let actioniserror = false;
					let datalist = data.CustomOperationFunList;
					for (var i in datalist) {
						let opttype = datalist[i].cusopttype;//操作方式
						let actionname = datalist[i].actionname;//url or actionname
						let actiontype = datalist[i].actiontype;//opentype or actiontype
						let actionfrom = datalist[i].actionfrom;//action
						let tempuserid = datalist[i].userid;//userid
						if(actioniserror){
							break ;
						}
						if (opttype === '0') {//打开URL
							actionname = getCustomOptUrlValues(actionname,tempuserid);
							if (actiontype === '0') { //新建页
								window.open(actionname,'divpage');
							} else if (actiontype === '1') { //弹出页
								//openFullWindowHaveBar
								window.openFullWindowForXtable(actionname);
								//window.open(actionname,'diypage2',params);
							} else if (actiontype === '2') { //当前页
								//top.location.href = actionname;
								getAntd().Modal.confirm({
									title:getLabel(131329,'信息确认'),
									content:getLabel(18877,"流程还没保存，如果离开，将会丢失数据，真的要离开吗？ "),
									okText:getLabel(826,'确定'),
									cancelText:getLabel(201,'取消'),
									onOk(){
										top.location.href = actionname;
									}
								});
								break ;
							}
						} else if (opttype === '1') {
							if((isremark=== '2'||isremark === '4') && (actiontype != '0' && actiontype != '3' && actiontype!= '10')){
								getAntd().message.error(getLabel(132382,'没有权限，无法操作'),3);
								continue ;
							}
							//流程相关操作
							if (actiontype === '0') {//刷新表单数据
								if(reqid>0) {
									globalStore.setLoading(false);
									Util.reloadRequestPage({requestid: reqid});
								}else{
									window.location.reload();
								}
							} else if (actiontype === '1') {//"提交/批准"
								doSubmitForm({actiontype:"requestOperation", src:"submit", needwfback:"1"});
							} else if (actiontype === '2') {//"提交至退回节点"
								this.doSubmitDirect('submit');
							} else if (actiontype === '3') {//"转发"
								//this.controlForward({'forwardflag': '1'});
								doReviewE9();
							} else if (actiontype === '4') {//"保存"
								this.doSave_nNew(false);
							} else if (actiontype === '5') {//"退回"
								this.doReject_New();
							} else if (actiontype === '6') {//"转办"
								//this.controlForward({'forwardflag': '3'});
                                doReview3();
							} else if (actiontype === '7') {//"意见征询"
								//this.controlForward({'forwardflag': '2'});
								doReview2();
							} else if (actiontype === '8') {//"超时设置"
								onNewOverTime();
							} else if (actiontype === '9') {//"强制归档"
								this.doDrawBack();
							} else if (actiontype === '10') {//"强制收回"
								this.doRetract();
							} else if (actiontype === '11') {//传阅
								//this.controlForward({'forwardflag': '4'});
								doChuanyue();
							}

						} else if (opttype === '2') {//字段赋值
							//TODO
						} else if (opttype === '3') {//附加操作
							const params1 = {
								requestId: reqid,
								nodeId: nodeid,
								workflowId: wfid,
								setid: menuid,
								actiontype: actiontype,
								actionname: actionname,
								actionfrom: actionfrom,
								f_weaver_belongto_userid: f_weaver_belongto_userid,
								f_weaver_belongto_usertype: f_weaver_belongto_usertype
							};

							API_REQ.runCustomOperationAction(params1).then(actiondata => {
								let flag = actiondata.CustomOperationActionResult.returnflag ;
								let msg = actiondata.CustomOperationActionResult.returnmsg ;
								if(flag === 'false') {
									getAntd().message.error(msg,3);
									actioniserror = true ;//出现异常后 后面的不执行
								}else{
									getAntd().message.success(msg,2);
								}
							});
						}
					}
				}
			});
		}catch (e) {
			if(window.console)	console.log(e);
		}

}

const getCustomOptUrlValues =(url,userid) =>{
	const { commonParam } = base.globalStore;
	const { requestid,workflowid,nodeid,formid } = commonParam;
	let regex = /\{[^\}]+\}/ ;

	//console.log("url = "+url);
	try {
		while (regex.test(url)) {
			//console.log("url = "+url);
			let str = regex.exec(url)[0];
			let e = "";
			//console.log("解析："+str);
			if (str != ''&&str!='{}') {
				let strnew = str.replace(new RegExp("\\{", "g"), "").replace(new RegExp("\\}", "g"), "");
				//console.log("str = "+str);
				if (strnew=='requestid') {
					e = requestid ;
				}else if (strnew=='workflowid') {
					e = workflowid ;
				}else if (strnew=='nodeid') {
					e = nodeid ;
				}else if (strnew=='userid') {
					e = userid ;
				}else if (strnew=='formid') {
					e = formid ;
				} else {
					try {
						e = WfForm.getFieldValue("field" + strnew);
					}catch (e) {
						e = "";
					}
					//console.log("strnew = "+strnew+" e = "+e);
				}
				try {
					url = url.replace(new RegExp("\\{"+strnew+"\\}", "g"), e);
				}catch (e) {
					//console.log(e);
				}
			}

		}
	}catch(e){

	}
	//console.log(url);
	return url ;
}
export const doImportWorkflow = ()=>{
	if(window.ImportWfBrowser && window.ImportWfBrowser.openModal){
		window.ImportWfBrowser.openModal();
	}
}
export const doTimeLimit = ()=>{
		const { requestid } = base.globalStore.commonParam;
		const { WeaDatePicker } = getEcCom();
		let buttons = [
			<Button type="ghost" onClick={() => {
				rejectdig.close();
			}}>
			  取消
			</Button>,
			<Button type="primary" onClick={() => {
				$.ajax({
					type: "GET",
					async: false,
					url: `/workflow/request/doTimeLimit.jsp?requestid=${requestid}&src=save&timelimit=${window[`limetdata_${requestid}`]}&flag=${Math.random()}`,
					success: function(data){
					}
				});
			  rejectdig.close();
			}}>
			  确定
			</Button>,
		  ];
		  var rejectdig=ecCom.WeaTools.createDialog({
			title: '办理限时',
			buttons: buttons,
			style:{width:400,height:400},
			destroyBodyOnClose:true,
			onCancel:() => {
			  rejectdig.close();
			}
		  }, 
		  [<div style={{margin:'20px'}}>
			  <div>办理期限:</div>
			  <WeaDatePicker
				  noInput
				value = {new Date()}
				onChange={(value) => {
					window[`limetdata_${requestid}`] = value;
					// console.log(value);
				}}
			  />
			</div>]
		  , (dialog) => {
			dialog.show();
		  });
		// var forwardurl = "/workflow/request/doTimeLimit.jsp?requestid="+requestid+"&flag=" + Math.random();
		// var dialog = new window.top.Dialog();
		// dialog.currentWindow = window;
		// dialog.Title = "办理限时";
		// dialog.Width = 400;
		// dialog.Height = 400;
		// dialog.Drag = true;
		// dialog.maxiumnable = true;
		// dialog.URL = forwardurl;
		// dialog.callback=function(data) {
		// dialog.close();
       	// };
		// dialog.show();
}